import utils from './utils/index';
import {
    Toast
} from './libs/util'
const wechat = require('./service/wechat.js')
const api = require('./service/api.js')
App({
    /**
     * Global shared
     * 可以定义任何成员，用于在整个应用中共享
     */
    data: {
        version: '0.1.0',
        currentCity: 'shanghai'
    },

    /**
     * WeChat API
     */
    wechat: wechat,

    /**
     *  API
     */
    request: api,
    Toast: Toast,
    /**
     * 生命周期函数--监听小程序初始化
     * 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
     */
    onLaunch: function () {
        this.utils = new utils()
        this.getUserInfo()
        // 调用API从本地缓存中获取数据
        var logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)

    },
    getUserInfo: function (cb) {
        var that = this
        if (this.globalData.userInfo) {
            typeof cb == "function" && cb(this.globalData.userInfo)
        } else {
            var app = this
            var userOpenid = ''
            app.wechat.login().then(res => {
                var code = res.code;
                if (code) {
                    var data = { "js_code": code }
                    return app.request.getOpenid(data);
                }
            }).then(res => {
                var openid = res.data.openid;
                if (openid) {
                    userOpenid = openid
                    return app.wechat.useOpenidGetInfo(userOpenid);
                }
            }).then(res => {
                console.log("登录成功")
                res.userInfo.openid = userOpenid
                res.userInfo.username = userOpenid
                res.userInfo.password = userOpenid
                var userInfo = { "userInfo": res.userInfo}
                console.log(userInfo)
                return app.request.saveUserinfo(userInfo);
            }).then(res => {
                console.log("保存成功")
                console.log(res)
                that.globalData.userInfo = res.data
                that.globalData.isLogin = true
                that.globalData.limited = res.data.limited
                typeof cb == "function" && cb(that.globalData.userInfo)
            }).catch(e => {
                console.log('失败');
                that.globalData.isLogin = false
                typeof cb == "function" && cb(null)
            })
        }
    },
    globalData: {
        limited:0,
        userInfo: null,
        isLogin: false,
        toTime: function (value) {
            value = parseInt(value)
            console.log(value)
            return (Math.floor(value / 60) + ':' + Math.floor(value % 60 + ':'))
        }
    },

    /**
     * 生命周期函数--监听小程序显示
     * 当小程序启动，或从后台进入前台显示，会触发 onShow
     */
    onShow () {
        console.log(' ========== Application is showed ========== ')
    },
    /**
     * 生命周期函数--监听小程序隐藏
     * 当小程序从前台进入后台，会触发 onHide
     */
    onHide () {
        console.log(' ========== Application is hid ========== ')
    }
})